package softwaredepartment.zxit.com.pt_3280cinandroid;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.socks.library.KLog;


import java.io.IOException;

import softwaredepartment.zxit.com.pt_3280cinandroid.Entity.MusicInfo;
import softwaredepartment.zxit.com.pt_3280cinandroid.Service.MusicService;
import softwaredepartment.zxit.com.pt_3280cinandroid.Utils.FileUtils;
import softwaredepartment.zxit.com.pt_3280cinandroid.Utils.MilliSecondDurtion2TimeFormat;

public class PlayMusicActivity extends Activity implements View.OnClickListener {

    private MusicService musicService;
    private SeekBar MusicSeekBar;
    private TextView MusicTime, MusicCurrentTime, MusicName;
    private ImageView btnPlayOrPause, ic_list, adjustVolume, MusicAlbumCover;
    private Handler handler;
    private String path;
    private Animation operatingAnim;
    private final int FILE_SELECT_CODE = 1;
    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicService = ((MusicService.MyBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService = null;
        }
    };

    private void bindServiceConnection() {
        Intent intent = new Intent(PlayMusicActivity.this, MusicService.class);
        startService(intent);
        bindService(intent, sc, this.BIND_AUTO_CREATE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_play_music);
        KLog.d("hint", "ready to new MusicService");
        //musicService = new MusicService();
        KLog.d("hint", "finish to new MusicService");
        //绑定服务
        bindServiceConnection();
        //初始化控件
        init();
        doPlayMusic();


    }

    private void doPlayMusic() {
//        MusicSeekBar.setProgress(musicService.mp.getCurrentPosition());
//        MusicSeekBar.setMax(musicService.mp.getDuration());
//        musicStatus = (TextView)this.findViewById(R.id.MusicStatus);
    }

    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (musicService.mp.isPlaying()) {
                MusicCurrentTime.setText(MilliSecondDurtion2TimeFormat.Ms2TimeStringFormat(musicService.mp.getCurrentPosition()));
                MusicSeekBar.setProgress(musicService.mp.getCurrentPosition());
            }

            MusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    //musicService.playOrPause();
                    musicService.mp.seekTo(seekBar.getProgress());
                    // musicService.playOrPause();
                }
            });
            handler.postDelayed(runnable, 100);
        }
    };


    @Override
    protected void onResume() {
        MusicSeekBar.setProgress(0);
        handler = new Handler();
        handler.post(runnable);
        musicService.mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                MediaPlayer mp1 = new MediaPlayer();
                try {
                    mp1.setDataSource(musicService.getMusicDir().get(musicService.getMusicDir().size() - 1).getMusicPath());
                    mp1.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                MusicCurrentTime.setText(MilliSecondDurtion2TimeFormat.Ms2TimeStringFormat(mp.getDuration()));
                btnPlayOrPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_music));
                MusicAlbumCover.clearAnimation();
            }
        });
        super.onResume();
    }

    private void init() {
        MusicAlbumCover = (ImageView) findViewById(R.id.MusicAlbumCover);
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.tip);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        MusicSeekBar = (SeekBar) findViewById(R.id.MusicSeekBar1);
        ic_list = (ImageView) findViewById(R.id.ic_list);
        adjustVolume = (ImageView) findViewById(R.id.adjustVolume);
        MusicTime = (TextView) this.findViewById(R.id.MusicTime);
        btnPlayOrPause = (ImageView) this.findViewById(R.id.BtnPlayorPause);
        MusicCurrentTime = (TextView) findViewById(R.id.MusicCurrentTime);
        MusicName = (TextView) findViewById(R.id.MusicName);
        MusicSeekBar.setEnabled(false);
        ic_list.setOnClickListener(this);
        adjustVolume.setOnClickListener(this);
        btnPlayOrPause.setOnClickListener(this);


    }

    @Override
    public void onDestroy() {
        unbindService(sc);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.BtnPlayorPause:
                if (musicService.getMusicDir().size() <= 0) {
                    Toast.makeText(this, "您的列表为空", Toast.LENGTH_SHORT).show();
                } else {
                    if (musicService.mp.isPlaying()) {
                        MusicAlbumCover.clearAnimation();
                        btnPlayOrPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_music));
                    } else {
                        if (operatingAnim != null) {
                            MusicAlbumCover.startAnimation(operatingAnim);
                        }
                        btnPlayOrPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_music));
                    }
                    musicService.playOrPause();

                }
                break;
            case R.id.ic_list:
                if (musicService.mp.isPlaying()) {
                    btnPlayOrPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_play_music));
                    musicService.playOrPause();
                }
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                Log.i("file", "===================");
                try {
                    startActivityForResult(intent, FILE_SELECT_CODE);
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(getApplication(), "Please install a File Manager.", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.adjustVolume:
                showPopupWindow(v);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    path = FileUtils.getPhotoPathFromContentUri(getApplication(), uri);
                    Log.i("File's Path is", path + "");
                    if (path != null) {
                        String splitPath[] = path.split("\\/");
                        String MusicNameInPath[] = splitPath[splitPath.length - 1].split("\\.");
                        MusicName.setText(MusicNameInPath[MusicNameInPath.length - 2]);
                        MusicInfo musicInfo = new MusicInfo();
                        musicInfo.setMusicPath(path);
                        musicService.addMusic(musicInfo);

                        try {
                            MediaPlayer mp = new MediaPlayer();
                            mp.setDataSource(musicService.getMusicDir().get(musicService.getMusicDir().size() - 1).getMusicPath());
                            mp.prepare();
                            MusicCurrentTime.setText("00:00");
                            MusicTime.setText(MilliSecondDurtion2TimeFormat.Ms2TimeStringFormat(mp.getDuration()));
                            MusicSeekBar.setMax(musicService.mp.getDuration());
                            MusicSeekBar.setProgress(0);
                            musicService.playOrPause();
                            if (operatingAnim != null) {
                                MusicAlbumCover.startAnimation(operatingAnim);
                            }
                            btnPlayOrPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause_music));
                            MusicSeekBar.setEnabled(true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getApplication(), "文件管理器异常。", Toast.LENGTH_LONG).show();
                    }


                }

                break;
        }
    }

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popwindow_adjust_volume, null);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        int popupWidth = view.getMeasuredWidth();    //  获取测量后的宽度
        int popupHeight = view.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        View ParentView = (View) view.getParent();
        int ParentViewHeight = ParentView.getHeight();
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, (location[0] + view.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight - ParentViewHeight+(ParentViewHeight-popupHeight)/2);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                KLog.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.mipmap.theme_dark_blue_bg));

        // 设置好参数之后再show
        //popupWindow.showAsDropDown(view);
    }


}
